﻿using System.Collections.Concurrent;
using System.Collections.Generic;

namespace LaoLuo
{
    public class ValueCounter<T>
    {
        private readonly ConcurrentDictionary<T, int> _dict;

        public ValueCounter(IEqualityComparer<T> equalityComparer = null)
        {
            _dict = equalityComparer == null ? new ConcurrentDictionary<T, int>() : new ConcurrentDictionary<T, int>(equalityComparer);
        }

        public int this[T value]
        {
            get
            {
                return !_dict.ContainsKey(value) ? 0 : _dict[value];
            }
        }

        public int Add(T value)
        {
            return _dict.AddOrUpdate(value, 1, (arg1, i) => ++i);
        }

        public bool Remove(T value)
        {
            int count;
            return _dict.TryRemove(value, out count);
        }
    }
}
